package com.zlt.miaosha.validator;

import com.zlt.miaosha.util.ValidatorUtil;
import org.springframework.util.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * @author zhoulitong
 * @date 2018/6/14
 * @description
 */
public class IsMobileValidator implements ConstraintValidator<IsMobile, String> {

    private boolean required = false;
    /**
     * 初始化方法可以拿到注解
     * @param constraintAnnotation
     */
    @Override
    public void initialize(IsMobile constraintAnnotation) {
        required = constraintAnnotation.required();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        //1、值是否为必须的
        if (required) {
            return ValidatorUtil.isMobile(value);
        } else {
            //2、值是否为空
            if (StringUtils.isEmpty(value)) {
                return true;
            } else {
                //3、如果值不为空，判断格式是否正确
                return ValidatorUtil.isMobile(value);
            }
        }
    }
}
